package cn.gdcp.saxtest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.TypeVariable;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class JsonActivity extends AppCompatActivity implements View.OnClickListener {
   Button jsonObjectBtn;
   Button gsonBtn;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json);
        initButtonView();
    }

    private void initButtonView() {
        jsonObjectBtn=findViewById(R.id.jsonobject_getJson_button);
        jsonObjectBtn.setOnClickListener(this);
        gsonBtn=findViewById(R.id.gson_getJson_button);
        gsonBtn.setOnClickListener(this);
    }

    public void onClick(View v) {
          switch (v.getId()){
              case R.id.jsonobject_getJson_button:
                 sendRequest();
                  break;
              case R.id.gson_getJson_button:
                  sendRequest();
                  break;

          }
    }

     private void sendRequest() {
        new Thread(new Runnable() {
            public void run() {
                try{
                    OkHttpClient client=new OkHttpClient();
                    Request request=new  Request.Builder().url("http://192.168.134.34:8080/ch1_ex1_news/get_data.json").build();
                    Response response=client.newCall(request).execute();
                  //  parseJsonWithJSONObject(response.body().string());
                       pareseJsonWithGson(response.body().string());
                }catch (Exception e)
                {
                    e.printStackTrace();
                }

            }
        }).start();
    }

    private void pareseJsonWithGson(String string) {
        Gson gson=new Gson();
        List<App> appList=gson.fromJson(string, new TypeToken<List<App>>(){}.getType());
        for (App app:appList){
            Log.e("id",app.id);
            Log.e("name",app.name);
            Log.e("version",app.version);
        }

    }

    private void parseJsonWithJSONObject(String string) {

        try{
            JSONArray jsonArray=new JSONArray(string);
        for(int i=0;i<jsonArray.length();i++){
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            String id=jsonObject.getString("id");
                String name=jsonObject.getString("name");
                String version=jsonObject.getString("version");
                Log.e("id",id);
                Log.e("name",name);
                Log.e("version",version);

            }
        }
            catch (Exception e){
                e.printStackTrace();
            }

        }

    }



